<%@page import="com.infolab.aims.domain.asset.AssetTransaction"%>
<%@ include file="/WEB-INF/views/taglib.jsp" %>
<h3>Issue Order Form</h3>	
	<form:form id="form" method="post" modelAttribute="assetTransaction"  cssClass="simpleForm">
		<form:hidden path="assetTransactionId" />
		<form:hidden path="accessDepartment.departmentId" />
		<div class="action">
	  	<c:choose>
	  		<c:when test="${assetTransaction.assetTransactionId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionStatus=='APPROVED'}">
	  			<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/EQUIPMENT" />" target='_blank' class="button">Print</a> 	  
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionId!=null}">
	  			<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/EQUIPMENT"/>" target='_blank' class="button">Print</a> 	  
  				<a href="<c:url value="/issueOrder/search" />" class="button">Back</a> 
  				
	  		</c:when>
	  		
	  	</c:choose>
	 	</div>	
		<div class="clear" style="height:1px">&nbsp;</div>
		<jsp:include page="/WEB-INF/views/message.jsp"></jsp:include>
	  	<fieldset>
	  		<legend>Issue Order Info</legend>
	  		<div class="span-12">
	  		<aims:column cssErrorClass="error" path="assetTransactionType" >
	  		<label>
	  			Issue Order Type  *
	 		</label>
	  		<form:select path="assetTransactionType" onchange="redirectAssetTransactionType(this.value)" id="assetTransactionType">
	  			<form:option value="IO">Issue Component</form:option>
	  			<form:option value="ET">Equipment Transfer</form:option>
	  			<form:option value="FT">Faulty Equipment Transfer</form:option>
	  			<form:option value="SOI">Sales</form:option>
	  			<form:option value="INH">In-House Repair</form:option>
	  		</form:select>
	  		<form:errors path="assetTransactionType"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="fromLocation.locationId" >
	  		<label>
	  			 Location
	 		</label>
	 		
	 		<c:choose>
	 			<c:when test="${empty assetTransaction.assetTransactionCode}">
	 				<form:select path="fromLocation.locationId" id="fromLocationId">
			  			<form:options items="${fromLocations}" itemLabel="locationName" itemValue="locationId" />
			  		</form:select>
	 			</c:when>
	 			<c:otherwise>
	 				${assetTransaction.fromLocation.locationName}
	 				<form:hidden path="fromLocation.locationId" id="fromLocationId" />
	 			</c:otherwise>
	 		</c:choose>
	  		<form:errors path="fromLocation.locationId"  cssClass="errorSimple" /> 
			</aims:column>
			
			<aims:column cssErrorClass="error" path="companyCode">
		  		<form:label path="companyCode">
		  			From Company Code
		 		</form:label>	
		 		
		 		<c:choose>
	 			<c:when test="${empty assetTransaction.assetTransactionCode}">
	 				<form:select id="companyCode" path="companyCode" class="companyCode">
		 				<form:options items="${globalCompanyCode}" itemValue="systemCode1" itemLabel="systemCodeValueDescription" />
		 			</form:select>
	 			</c:when>
	 			<c:otherwise>
	 				${assetTransaction.companyCode}
	 				<form:hidden path="companyCode" id="companyCode" />
	 			</c:otherwise>
	 		</c:choose>
		  	<form:errors path="companyCode"  cssClass="errorSimple" />	 
			</aims:column>	
			
			
				<aims:column cssErrorClass="error" path="toCompanyCode">
		  		<form:label path="toCompanyCode">
		  			To Company Code
		 		</form:label>		 		
		 		<c:choose>
	 			<c:when test="${empty assetTransaction.assetTransactionCode}">
	 				<form:select id="toCompanyCode" path="toCompanyCode" class="toCompanyCode">
		 				<form:options items="${globalCompanyCode}" itemValue="systemCode1" itemLabel="systemCodeValueDescription" />
		 			</form:select>
	 			</c:when>
	 			<c:otherwise>
	 				${assetTransaction.toCompanyCode}
	 				<form:hidden path="toCompanyCode" id="toCompanyCode" />
	 			</c:otherwise>
	 		</c:choose>
		  	<form:errors path="toCompanyCode"  cssClass="errorSimple" />	 
			</aims:column>	
			
			
			</div>
			<div class="span-8">
			<aims:column cssErrorClass="error" path="assetTransactionCode"  cssClass="clearfix">
	  		<label>
	  			Issue Order Code  
	 		</label>
	  			${assetTransaction.assetTransactionCode } 
			</aims:column>
			<aims:column cssErrorClass="error" path="assetTransactionCode" cssClass="clearfix">
	  		<label>
	  			Issue Order Date  
	 		</label>
	 			<fmt:formatDate value="${assetTransaction.dateCreated}" pattern="${globalDateFormatJava}"/> 
			</aims:column>
			<aims:column cssErrorClass="error" path="assetTransactionStatus" cssClass="clearfix">
	  		<label>
	  			Issue Order Status
	 		</label>
	 			${assetTransaction.assetTransactionStatus} 
			</aims:column>
			</div>
			</fieldset>
			<fieldset>
			<c:if test="${empty assetTransaction.assetTransactionId || assetTransaction.assetTransactionStatus!='APPROVED'}">
				
			
			<div class="span-8 minLabel">
	  		<p class="clearfix">
	  		<label> Asset Model</label>
		  	<select name="assetModelId" id="assetModelId" class="assetModelId">
		  	</select>	
		  	</p>
		  	<p class="clearfix">
		  	<label>Serial No </label> 
	  		<input name="serialNo" id="serialNo" type="text" />
	  		</p>
	  		<p class="clearfix">
	  				  		
	  		<a onclick="searchEquipment()" class="button">Search</a>
	  		
	  		</p> 
	  		
	  		<table id="searchResult" class="gridSearch">
	  			<thead>
	  				<tr>
	  					<th title="Click below hyperlink to add to list"> + Add To List</th>
	  				</tr>
	  			</thead>
	  			<tbody>
	  			 
	  			</tbody>
	  		</table>	
	  		
			</div>
			</c:if>
			
			<c:choose>
				<c:when test="${empty assetTransaction.assetTransactionId || assetTransaction.assetTransactionStatus!='APPROVED'}">
					<div class="span-14">
				</c:when>
				<c:otherwise>
					<div> 	
				</c:otherwise>	
				
			</c:choose>
			
			  		
	  	
	  		<table id="equipmentTable" class="gridSearch">
	  		
	  		<caption id="header" class="captionLeft">Total number of items : 
		  		<span id="totalItems"></span></caption>
		  		
	  			<thead>
	  				<tr>
	  					<c:if test="${assetTransaction.assetTransactionStatus!='APPROVED'}">
	  					<th>Remove</th>
	  					</c:if>
	  					<th>Asset Model</th>
	  					<th>Serial No</th>
	  					<th>Remarks</th>	
	  					
	  				</tr>
	  			</thead>
	  			<tbody>
	  			<c:forEach items="${assetTransaction.assetTransactionItems}" var="item" varStatus="status">
	  				<tr <c:if test="${(status.count%2)==0 }">class="alt"</c:if>>
	  				<c:if test="${assetTransaction.assetTransactionStatus!='APPROVED'}">
	  				<td> 
	  					<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
							<img align="absmiddle" src="${imageUrl}/icon_delete.png">
						</a>
	  				</td>
	  				</c:if>
	  				<td>
	  				<input name="assetTransactionItems[${status.index}].assetTransactionItemPK.assetTransaction.assetTransactionId" type="hidden" value="${assetTransaction.assetTransactionId}" />
	  				<input name="assetTransactionItems[${status.index}].assetTransactionItemPK.itemNo" type="hidden" value="${item.assetTransactionItemPK.itemNo}" /> 
	  				<input name="assetTransactionItems[${status.index}].assetModel.assetModelId" type="hidden" class="assetModelId" value="${item.assetModel.assetModelId}" />
					<input name="assetTransactionItems[${status.index}].serialNo" type="hidden"  value="${item.serialNo}" class="serialNo" />
					<input name="assetTransactionItems[${status.index}].deleted" type="hidden" class="deleted" value="${item.deleted}" />
					<input name="assetTransactionItems[${status.index}].assetTransactionStatus" type="hidden"  value="${item.assetTransactionStatus}" />
					
	  				
		  					<c:out value="${item.assetModel.assetModelCode}-${item.assetModel.assetModelName}" />
		  					</td>
		  					
	  				<td>${item.serialNo}</td>
	  				<td>
	  				${item.remarks}
	  				</td>
	  				
	  									
	  					
	  				
	  				</tr>
	  			</c:forEach>
	  			</tbody>
	  		</table>
	  
	  		</div>
	  		
			</fieldset>
			
      <div class="action">
	  	<c:choose>
	  		<c:when test="${assetTransaction.assetTransactionId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionStatus=='APPROVED'}">
	  			<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/EQUIPMENT" />" target='_blank' class="button">Print</a> 	  
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionId!=null}">
	  			<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/EQUIPMENT"/>" target='_blank' class="button">Print</a> 	  
  				<a href="<c:url value="/issueOrder/search" />" class="button">Back</a> 
  				
	  		</c:when>
	  		
	  	</c:choose>
	 </div>	
	</form:form>
	
	<table id="tmpTable" style="visibility:hidden">
		<tr class="new">
		<td>
	  		<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
				<img align="absmiddle" src="${imageUrl}/icon_delete.png">
			</a>
	  	</td> 
		<td>
		<input name="assetTransactionItems.assetModel.assetModelId" type="hidden" class="assetModelId" />
		<input name="assetTransactionItems.deleted" type="hidden"  class="deleted"/>
		<input name="assetTransactionItems.serialNo" type="hidden" class="serialNo" />
		<input name="assetTransactionItems.assetTransactionItemPK.itemNo" type="hidden"  />
		<span class="assetModelName"></span>
	  	</td>
	  	<td>
	  	<span class="serialNo"></span>
	  	</td>
	  	<td>
	  	<textarea name="assetTransactionItems.remarks" rows="2" cols="20"></textarea>
	  	</td>
	  	<c:if test="${assetTransaction.assetTransactionId!=null}">
	  	<td>
			<input name="assetTransactionItems.assetTransactionStatus" type="hidden"  />
			<input type="checkbox" onchange="updateStatus(this)" value="1"  />
	  	</td>
	  	</c:if>
	  	
		</tr>
	</table>
	<script type="text/javascript" src="<spring:url value="/resources/js/select-option-disabled-emulation.js" />"></script>
	<script type="text/javascript">
		var validateRows = 0;
		var finalValidRowCount = 0;
		$(document).ready(function() {
			
			var assetModelEquip;
			$.getJSON("<c:url value="/ajax/asset/equipment"></c:url>", function(data) {
				
				assetModelEquip = data;
				for(var i=0;i<assetModelEquip.length;i++)
				{
					$('#assetModelId').
			          append($("<option></option>").
			          attr("value",assetModelEquip[i].assetModelId).
			          text(assetModelEquip[i].assetModelName));
				}
				
				checkCompanyCodeDropDown();
			});
			
			
					
			var et = $('#equipmentTable tbody tr');
			if(et){
			finalValidRowCount = et.size();
			}
			hideHiddenRows();
			
			
			
			if(finalValidRowCount<=0){
				$('#header').hide();				
			}
			else{			
				$('#header').show();
				$('#totalItems').text(finalValidRowCount);
			}
		});
		
		function formSubmit(){
			if(validateForm()){
				if(confirm('You are going to do sales of items issue order, please click OK to proceed')){
				var form = $('#form');				
				form.submit();
				}
			}
		}
		
		function validateForm(){
			var res = true;
			var companyCode = $('#companyCode').val();
			var toCompanyCode = $('#toCompanyCode').val();
			if(finalValidRowCount<=0)
			{		 
				alert(" No valid record to start processing");
				res = false;
				return res;
				
			}
			else if(companyCode == toCompanyCode)
				{
					alert(" From Company Code and To Company Code should not be equal ");
					res = false;
					return res;
				}
			
			if(finalValidRowCount == 0)
			{
				alert(" No valid record to start processing");
			res = false;
			return res;
			
			}
			return res;
			
		}
		
	function checkCompanyCodeDropDown(){
			
		
			if(validateRows<=0)
				$("#companyCode option").not(":selected").attr("disabled",false);	
				
			else
				$("#companyCode option").not(":selected").attr("disabled",true);
								
			<c:if test="${empty assetTransaction.assetTransactionCode}">
					emulate(document.getElementById('companyCode'));
			</c:if>
					
		}
		
		
		function hideHiddenRows()
		{			
		var table = $(' #equipmentTable tbody tr');
			
			var hiddenRow=false;
			var modelId;
			table.each(
					function () {
						
					hiddenRow = $('.deleted',this).val();
					 modelId = $('.assetModelId',this).val();
					
						if(hiddenRow=='true'){
							$(this).hide();
							finalValidRowCount--;
							
						}
					}
					);
			
		}
		
		function addRow(obj)
		{
			var serialNo = $(obj).text();
			
			for(i=0;i<assetSerialNo.length;i++){
				if(assetSerialNo[i].assetEquipmentPK.serialNo==serialNo)
				{
					var row = $('#tmpTable tr').clone();
					
					var rowSize = $('#equipmentTable tbody tr').size();
					
					var assetModelId = assetSerialNo[i].assetEquipmentPK.assetModel.assetModelId;
					var assetModelName = assetSerialNo[i].assetEquipmentPK.assetModel.assetModelName;
					
					$('input[name=assetTransactionItems.deleted]',row).attr('name','assetTransactionItems['+rowSize+'].deleted').val(false);
					$('input[name=assetTransactionItems.assetModel.assetModelId]',row).attr('name','assetTransactionItems['+rowSize+'].assetModel.assetModelId').val(assetModelId);
					$('input[name=assetTransactionItems.serialNo]',row).attr('name','assetTransactionItems['+rowSize+'].serialNo').val(serialNo);
					
					$('input[name=assetTransactionItems.assetTransactionItemPK.itemNo]',row).attr('name','assetTransactionItems['+rowSize+'].assetTransactionItemPK.itemNo');
					$('textarea[name=assetTransactionItems.remarks]',row).attr('name','assetTransactionItems['+rowSize+'].remarks');
					
					$('.assetModelName',row).text(assetModelName);
					$('span.serialNo',row).text(serialNo);
					
					<c:if test="${assetTransaction.assetTransactionId!=null}">
						$('input[name=assetTransactionItems.assetTransactionStatus]',row).attr('name','assetTransactionItems['+rowSize+'].assetTransactionStatus');
					</c:if>
					
					row.appendTo('#equipmentTable tbody');
					finalValidRowCount++;
					$('#totalItems').text(finalValidRowCount);
					$('#header').show();
					validateRows++;
					checkCompanyCodeDropDown();
					
					$(obj).parent().hide();
					break;					
				}
				
			}
			
		}
		
		function removeRow(obj)
		{
			var ctx = $(obj).parent().parent();
			
				$('input[name*=deleted]',ctx).val('true');
				ctx.hide();
				validateRows--;
				checkCompanyCodeDropDown();
				finalValidRowCount--;
				$('#totalItems').text(finalValidRowCount);
				$('#header').show();
		}
		
		
		var assetSerialNo;
		var assetTransactionType ;
		function searchEquipment()
		{
			var assetModelId =  $('#assetModelId').val();
			var serialNo =  $('#serialNo').val();
			var locationId = $('#fromLocationId').val();
			var companyCode = $('#companyCode').val();
			
			
			var searchResultTable =$('#searchResult tbody') ; 
			searchResultTable.html('');
			
			assetTransactionType = $('#assetTransactionType').val();
			
			
			var serialNoUrl = "<c:url value="/ajax/equipment/active"></c:url>?assetModelId="+assetModelId+"&serialNo="+serialNo+"&locationId="+locationId+"&companyCode="+companyCode;
				
			$.getJSON(serialNoUrl, function(data) {
				
				assetSerialNo = data;
				
				if(data.length==0)
					alert('No serial no found');
				
				var existingSerialNo = $('.serialNo');
				var arrSerialNo = new Array();
				if(existingSerialNo )
				{
					existingSerialNo.each(function(data){
						if($(this).val()!='' && $(this).parent().is(':visible'))
							arrSerialNo.push($(this).val());
						
					});
				}
				
				for(i=0;i<data.length;i++){
					if($.inArray(data[i].assetEquipmentPK.serialNo,arrSerialNo)==-1)
						$("<tr><td><a href='javascript:void(0)' onclick='addRow(this)'>"+data[i].assetEquipmentPK.serialNo+"</a></td></tr>").appendTo(searchResultTable);
					
				}
				
			});
		}
		
		function updateStatus(obj)
		{
			if($(obj).is(':checked'))
			{
				$(obj).prev().val('<%=AssetTransaction.TRANSACTIONSTATUS_APPROVED%>');
			}
			else
				$(obj).prev().val('<%=AssetTransaction.TRANSACTIONSTATUS_PENDING%>'); 
		}

		function redirectAssetTransactionType(value)
		{
			if(value=='IO'){
				location.href='<c:url value="/issueOrder/create"></c:url>';
			}else if(value=='ET'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=ET"></c:url>';
			}
			else if(value=='SOI'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=SOI"></c:url>';
			}
			else if(value=='INH'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=INH"></c:url>';
			}
			else{
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=FT"></c:url>';
			}
		}
		
		
		 
	</script>
